﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using FBroSharp;                    // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl
using FBroSharp.Lib;                // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;              // ⚠️ REQUIRED! FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.Const;              // FBroSharpTransitionType
using FBroSharp.DataType;           // ⚠️ REQUIRED! FBroSharpEventDisableControl
using FBroSharp.Event;
using FBroSharp.Callback;              // FBroSharpBrowserEvent

namespace 文件下载管理器
{
    public partial class Form1 : Form
    {
        // 浏览器标识符
        private const string BROWSER_USER_FLAG = "download_browser";
        
        // 下载项信息类
        private class DownloadInfo
        {
            public uint DownloadId { get; set; }
            public string FileName { get; set; }       // ⚠️ 文件名（用作唯一标识符）
            public string FullPath { get; set; }
            public long TotalBytes { get; set; }
            public long ReceivedBytes { get; set; }
            public int PercentComplete { get; set; }
            public long Speed { get; set; }
            public string Status { get; set; }
            public DateTime StartTime { get; set; }
            public ListViewItem ListItem { get; set; }
            public IFBroSharpDownloadItemCallback Callback { get; set; }
            public bool IsComplete { get; set; }
            public bool IsCanceled { get; set; }
            public bool IsPaused { get; set; }
        }

        // 下载项字典（使用文件名作为Key，因为文件名在整个下载过程中是稳定的）
        private Dictionary<string, DownloadInfo> _downloads = new Dictionary<string, DownloadInfo>();
        private Timer _updateTimer;
        private bool _isDownloadPanelVisible = false;

        public Form1()
        {
            InitializeComponent();
            
            // 初始化更新定时器
            _updateTimer = new Timer();
            _updateTimer.Interval = 500; // 每500ms更新一次
            _updateTimer.Tick += UpdateTimer_Tick;
            _updateTimer.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 创建嵌入式浏览器
                CreateBrowser();
                
                UpdateStatus("浏览器正在初始化...");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 创建浏览器
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowsInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ 嵌入到Panel中
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "下载管理浏览器"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    "https://www.baidu.com",
                    windowsInfo,
                    settings,
                    default,        // request_context
                    default,        // extra_info
                    browserEvent,
                    default,        // ⚠️ CRITICAL: 使用 default 而不是 null（struct类型）
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    Console.WriteLine("✅ 浏览器创建成功");
                }
                else
                {
                    MessageBox.Show("浏览器创建失败！", "错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL: 处理嵌入式浏览器的窗口大小调整
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    // ⚠️ 调整浏览器大小以匹配容器
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 转到URL
        /// </summary>
        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                NavigateToUrl(txtUrl.Text);
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
        }

        private void NavigateToUrl(string url)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                    return;

                // 补全协议
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "https://" + url;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null && frame.IsValid)
                    {
                        frame.LoadURL(url);
                        UpdateStatus($"正在导航到: {url}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新页面
        /// </summary>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.Reload();
                    UpdateStatus("正在刷新页面...");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 添加下载任务
        /// </summary>
        private void btnAddDownload_Click(object sender, EventArgs e)
        {
            // 显示下载URL输入对话框
            string downloadUrl = Microsoft.VisualBasic.Interaction.InputBox(
                "请输入要下载的文件URL：",
                "添加下载任务",
                "https://",
                -1, -1);

            if (!string.IsNullOrWhiteSpace(downloadUrl))
            {
                // 导航到下载页面触发下载
                NavigateToUrl(downloadUrl);
                ShowDownloadPanel();
            }
        }

        /// <summary>
        /// 显示/隐藏下载管理器面板
        /// </summary>
        private void btnDownloadManager_Click(object sender, EventArgs e)
        {
            _isDownloadPanelVisible = !_isDownloadPanelVisible;
            
            if (_isDownloadPanelVisible)
            {
                ShowDownloadPanel();
            }
            else
            {
                HideDownloadPanel();
            }
        }

        private void ShowDownloadPanel()
        {
            panelDownloads.Visible = true;
            _isDownloadPanelVisible = true;
            btnDownloadManager.Text = "隐藏下载管理器";
        }

        private void HideDownloadPanel()
        {
            panelDownloads.Visible = false;
            _isDownloadPanelVisible = false;
            btnDownloadManager.Text = "下载管理器";
        }

        /// <summary>
        /// 清空下载列表
        /// </summary>
        private void btnClearDownloads_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show(
                "确定要清空所有已完成的下载记录吗？",
                "确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                // 只移除已完成的下载项
                var completedPaths = new List<string>();
                foreach (var kvp in _downloads)
                {
                    if (kvp.Value.IsComplete || kvp.Value.IsCanceled)
                    {
                        completedPaths.Add(kvp.Key);
                    }
                }

                foreach (var path in completedPaths)
                {
                    if (_downloads.TryGetValue(path, out var info))
                    {
                        lstDownloads.Items.Remove(info.ListItem);
                        _downloads.Remove(path);
                    }
                }

                UpdateDownloadCount();
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL: 处理下载开始前事件
        /// </summary>
        public void HandleBeforeDownload(uint downloadId, string suggestedName, 
            long totalBytes, IFBroSharpBeforeDownloadCallback callback)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => HandleBeforeDownload(downloadId, suggestedName, totalBytes, callback)));
                return;
            }

            try
            {
                // 设置默认下载路径
                string downloadPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                    "Downloads");

                if (!Directory.Exists(downloadPath))
                {
                    Directory.CreateDirectory(downloadPath);
                }

                string fullPath = Path.Combine(downloadPath, suggestedName);

                // 调用回调设置下载路径
                callback.Continue(fullPath, false);

                // 创建下载信息
                var downloadInfo = new DownloadInfo
                {
                    DownloadId = downloadId,
                    FileName = suggestedName,
                    FullPath = fullPath,
                    TotalBytes = totalBytes,
                    ReceivedBytes = 0,
                    PercentComplete = 0,
                    Speed = 0,
                    Status = "准备中",
                    StartTime = DateTime.Now,
                    IsComplete = false,
                    IsCanceled = false,
                    IsPaused = false
                };

                // 添加到ListView
                var item = new ListViewItem(new[]
                {
                    suggestedName,
                    FormatFileSize(downloadInfo.TotalBytes),
                    "0%",
                    "0 KB/s",
                    "准备中",
                    fullPath
                });
                
                downloadInfo.ListItem = item;
                lstDownloads.Items.Add(item);

                // ⚠️ 使用文件名作为Key（文件名在整个下载过程中是稳定的）
                _downloads[suggestedName] = downloadInfo;

                // 显示下载面板
                ShowDownloadPanel();
                
                UpdateDownloadCount();
                UpdateStatus($"开始下载: {suggestedName}");
                
                Console.WriteLine($"[Download] ✅ 开始下载: {suggestedName}");
                Console.WriteLine($"  文件名: {suggestedName}");
                Console.WriteLine($"  保存到: {fullPath}");
                if (downloadInfo.TotalBytes > 0)
                {
                    Console.WriteLine($"  文件大小: {FormatFileSize(downloadInfo.TotalBytes)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Download] ❌ 处理下载开始失败: {ex.Message}");
                Console.WriteLine($"[Download] 堆栈跟踪: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL: 处理下载进度更新
        /// </summary>
        public void HandleDownloadUpdated(uint downloadId, string suggestedName, string fullPath,
            long receivedBytes, long totalBytes, int percentComplete, long currentSpeed,
            bool isComplete, bool isCanceled, bool isInProgress, IFBroSharpDownloadItemCallback callback)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => HandleDownloadUpdated(downloadId, suggestedName, fullPath,
                    receivedBytes, totalBytes, percentComplete, currentSpeed,
                    isComplete, isCanceled, isInProgress, callback)));
                return;
            }

            try
            {
                Console.WriteLine($"[Form1] 🔍 查找下载项:");
                Console.WriteLine($"  ID: {downloadId}");
                Console.WriteLine($"  文件名: {suggestedName ?? "(空)"}");
                Console.WriteLine($"  路径: {fullPath ?? "(空)"}");
                Console.WriteLine($"  📦 字典中共有 {_downloads.Count} 个下载项");
                
                DownloadInfo info = null;
                
                // ⚠️ 策略1: 使用完整路径的文件名部分查找
                if (!string.IsNullOrEmpty(fullPath))
                {
                    string fileNameFromPath = Path.GetFileName(fullPath);
                    if (_downloads.TryGetValue(fileNameFromPath, out info))
                    {
                        Console.WriteLine($"[Form1] ✅ 通过完整路径找到: {info.FileName}");
                    }
                }
                
                // ⚠️ 策略2: 使用建议文件名查找
                if (info == null && !string.IsNullOrEmpty(suggestedName))
                {
                    if (_downloads.TryGetValue(suggestedName, out info))
                    {
                        Console.WriteLine($"[Form1] ✅ 通过建议文件名找到: {info.FileName}");
                    }
                }
                
                // ⚠️ 策略3: 使用下载ID查找（如果有）
                if (info == null && downloadId > 0)
                {
                    info = _downloads.Values.FirstOrDefault(d => d.DownloadId == downloadId);
                    if (info != null)
                    {
                        Console.WriteLine($"[Form1] ✅ 通过下载ID找到: {info.FileName}");
                    }
                }
                
                // ⚠️ 策略4: 如果只有一个未完成的下载，直接使用
                if (info == null && _downloads.Count == 1)
                {
                    info = _downloads.Values.First();
                    Console.WriteLine($"[Form1] ✅ 使用唯一下载项: {info.FileName}");
                }
                
                if (info == null)
                {
                    Console.WriteLine($"[Form1] ❌ 未找到下载项");
                    Console.WriteLine($"  字典中的文件名:");
                    foreach (var key in _downloads.Keys.Take(3))
                    {
                        Console.WriteLine($"    - {key}");
                    }
                    return;
                }
                
                // 更新真实的下载ID（第一次可能是0）
                if (info.DownloadId == 0 && downloadId > 0)
                {
                    info.DownloadId = downloadId;
                    Console.WriteLine($"[Form1] 🔄 更新下载ID: {downloadId}");
                }
                
                // 更新完整路径（第一次可能是空）
                if (string.IsNullOrEmpty(info.FullPath) && !string.IsNullOrEmpty(fullPath))
                {
                    info.FullPath = fullPath;
                    Console.WriteLine($"[Form1] 🔄 更新完整路径: {fullPath}");
                }

                // 保存回调以供暂停/恢复/取消使用
                info.Callback = callback;

                // 更新下载信息
                info.ReceivedBytes = receivedBytes;
                info.TotalBytes = totalBytes;
                info.PercentComplete = percentComplete;
                info.Speed = currentSpeed;

                // 只在有显著变化时输出日志（避免刷屏）
                if (info.PercentComplete % 10 == 0 || info.PercentComplete == 100)
                {
                    Console.WriteLine($"[Form1] 📊 {info.FileName}: {info.PercentComplete}% - {FormatSpeed(info.Speed)}");
                }

                // 更新下载状态（使用传入的参数）
                if (isComplete)
                {
                    info.Status = "已完成";
                    info.IsComplete = true;
                    Console.WriteLine($"[Form1] ✅ {info.FileName} 下载完成！");
                    UpdateStatus($"下载完成: {info.FileName}");
                }
                else if (isCanceled)
                {
                    info.Status = "已取消";
                    info.IsCanceled = true;
                    Console.WriteLine($"[Form1] ❌ {info.FileName} 已取消");
                }
                else if (isInProgress)
                {
                    if (info.IsPaused)
                    {
                        info.Status = "已暂停";
                    }
                    else
                    {
                        info.Status = "下载中";
                    }
                }
                else
                {
                    info.Status = "等待中";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Form1] ❌ 更新下载进度失败: {ex.Message}");
                Console.WriteLine($"[Form1] 堆栈跟踪: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 定时更新UI
        /// </summary>
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                foreach (var kvp in _downloads)
                {
                    var info = kvp.Value;
                    if (info.ListItem != null)
                    {
                        
                        info.ListItem.SubItems[0].Text = info.FileName;
                        info.ListItem.SubItems[1].Text = FormatFileSize(info.TotalBytes);
                        info.ListItem.SubItems[2].Text = $"{info.PercentComplete}%";
                        info.ListItem.SubItems[3].Text = FormatSpeed(info.Speed);
                        info.ListItem.SubItems[4].Text = info.Status;
                        info.ListItem.SubItems[5].Text = info.FullPath;
                        
                        // 根据状态设置颜色
                        if (info.IsComplete)
                        {
                            info.ListItem.ForeColor = Color.Green;
                        }
                        else if (info.IsCanceled)
                        {
                            info.ListItem.ForeColor = Color.Red;
                        }
                        else if (info.IsPaused)
                        {
                            info.ListItem.ForeColor = Color.Orange;
                        }
                        else
                        {
                            info.ListItem.ForeColor = Color.Black;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[Timer] ⚠️ 警告: 下载项 {info.FileName} 的ListItem为null");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Timer] ❌ 更新UI失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 暂停下载
        /// </summary>
        private void btnPauseDownload_Click(object sender, EventArgs e)
        {
            if (lstDownloads.SelectedItems.Count > 0)
            {
                var item = lstDownloads.SelectedItems[0];
                var info = _downloads.Values.FirstOrDefault(d => d.ListItem == item);
                
                if (info != null && !info.IsComplete && !info.IsCanceled && !info.IsPaused)
                {
                    if (info.Callback != null)
                    {
                        info.Callback.Pause();
                        info.IsPaused = true;
                        info.Status = "已暂停";
                        UpdateStatus($"已暂停下载: {info.FileName}");
                    }
                }
            }
        }

        /// <summary>
        /// 恢复下载
        /// </summary>
        private void btnResumeDownload_Click(object sender, EventArgs e)
        {
            if (lstDownloads.SelectedItems.Count > 0)
            {
                var item = lstDownloads.SelectedItems[0];
                var info = _downloads.Values.FirstOrDefault(d => d.ListItem == item);
                
                if (info != null && info.IsPaused)
                {
                    if (info.Callback != null)
                    {
                        info.Callback.Resume();
                        info.IsPaused = false;
                        info.Status = "下载中";
                        UpdateStatus($"已恢复下载: {info.FileName}");
                    }
                }
            }
        }

        /// <summary>
        /// 取消下载
        /// </summary>
        private void btnCancelDownload_Click(object sender, EventArgs e)
        {
            if (lstDownloads.SelectedItems.Count > 0)
            {
                var result = MessageBox.Show(
                    "确定要取消此下载吗？",
                    "确认",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    var item = lstDownloads.SelectedItems[0];
                    var info = _downloads.Values.FirstOrDefault(d => d.ListItem == item);
                    
                    if (info != null && !info.IsComplete)
                    {
                        if (info.Callback != null)
                        {
                            info.Callback.Cancel();
                            info.IsCanceled = true;
                            info.Status = "已取消";
                            UpdateStatus($"已取消下载: {info.FileName}");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 打开下载文件夹
        /// </summary>
        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            if (lstDownloads.SelectedItems.Count > 0)
            {
                var item = lstDownloads.SelectedItems[0];
                var info = _downloads.Values.FirstOrDefault(d => d.ListItem == item);
                
                if (info != null)
                {
                    try
                    {
                        string folder = Path.GetDirectoryName(info.FullPath);
                        if (Directory.Exists(folder))
                        {
                            Process.Start("explorer.exe", folder);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"无法打开文件夹: {ex.Message}", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void lstDownloads_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool hasSelection = lstDownloads.SelectedItems.Count > 0;
            btnPauseDownload.Enabled = hasSelection;
            btnResumeDownload.Enabled = hasSelection;
            btnCancelDownload.Enabled = hasSelection;
            btnOpenFolder.Enabled = hasSelection;
        }

        /// <summary>
        /// 更新下载数量
        /// </summary>
        private void UpdateDownloadCount()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(UpdateDownloadCount));
                return;
            }

            int activeCount = _downloads.Count(d => !d.Value.IsComplete && !d.Value.IsCanceled);
            int totalCount = _downloads.Count;
            
            lblDownloadTitle.Text = $"下载管理器 ({activeCount} 个活动任务 / 共 {totalCount} 个)";
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            if (bytes <= 0) return "未知";
            
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            int order = 0;
            double size = bytes;
            
            while (size >= 1024 && order < sizes.Length - 1)
            {
                order++;
                size /= 1024;
            }
            
            return $"{size:0.##} {sizes[order]}";
        }

        /// <summary>
        /// 格式化下载速度
        /// </summary>
        private string FormatSpeed(long bytesPerSecond)
        {
            if (bytesPerSecond <= 0) return "0 KB/s";
            
            return FormatFileSize(bytesPerSecond) + "/s";
        }

        #region UI更新方法（从BrowserEvent调用）

        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }

            lblStatus.Text = message;
            Console.WriteLine($"[Status] {message}");
        }

        public void UpdateAddressBar(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateAddressBar(url)));
                return;
            }

            txtUrl.Text = url;
        }

        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            this.Text = $"{title} - 文件下载管理器";
        }

        public void UpdateLoadingState(bool isLoading)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateLoadingState(isLoading)));
                return;
            }

            btnRefresh.Enabled = !isLoading;
            btnGo.Enabled = !isLoading;
        }

        #endregion

        /// <summary>
        /// 窗体关闭前
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _updateTimer?.Stop();
                _updateTimer?.Dispose();

                // 关闭浏览器
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(false, false);
                }

                Console.WriteLine("✅ 窗体关闭完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭窗体时出错: {ex.Message}");
            }
        }
    }
}
